package app;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import fay.frame.fast.F;
import fay.frame.service.S;
import fay.frame.ui.U;
import me.leolin.shortcutbadger.ShortcutBadger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.NetworkType;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
//import com.bugtags.library.Bugtags;

/**
 * <b>公司:</b> EE教育有限公司</p> <b>作者:</b> 肖飞</p> <b>日期:</b> 2014-12-10 下午4:46:40</p>
 * <b>版本:</b> V1.0</p> <b>描述:</b> COCOFrame基类.
 * </p>继承自此类的Activity可以直接使用COCOFrame框架(即可直接使用S,F,U类的所有方法).
 * </p>不继承自此类亦可通过S.init()和F = new
 * F(this);进行框架初始化.如果想使用DisplayService显示服务类,则需要单独初始化S.DisplayService.init(this);
 * </p>此类实现了OnClickListener
 */
public abstract class BaseActivity extends FragmentActivity implements
		OnClickListener {
	protected F F;
	private boolean ifShowExit = false;
	public static final ArrayList<Activity> activityList = new ArrayList<Activity>();
	/**
	 * 
	 * 继承自BaseActivity的Activity按返回键时,会弹出"确定退出应用吗?"的对话框.</p>取消此效果可直接覆盖onKeyDown方法
	 */
	public Activity currentActivity = null;
	private long preKeyBackTime = 0;
	private int exitImgID,top,top2,width,hight;
	private float density;
	private String exitMsg;
	private SharedPreferences sharedPreferences;
	private LinearLayout mNetErrorView;
	private RelativeLayout public_layout_top;
	private View view;
	//判断剪切板 是否改变
	private static boolean isOne;
	/**
	 * 
	 * 所有继承自BaseActivity的Activity都会被加入到队列中,调用此方法可以finish()所有子Activity,
	 * 同时会kill掉APP进程
	 */
	public void finishAll() {
		for (int i = 0; i < activityList.size(); i++) {
			activityList.get(i).finish();
		}
//		S.AppService.killAppProcess();
		activityList.clear();
	}

	/**
	 * 关闭某个activity
	 * 
	 * @param acitivityName
	 *            eg:com.istudy.order.choosefinance.activity.
	 *            ChooseFinanceActivity
	 */
	public void colseActivity(String acitivityName) {
		ArrayList<Activity> removeList = new ArrayList<Activity>();
		for (Activity activity : activityList) {
			if (activity.getClass().getName().equals(acitivityName)) {
				activity.finish();
				removeList.add(activity);
			}
		}
		for (Activity activity : removeList) {
			activityList.remove(activity);
		}
	}



	/**
	 * 
	 * 本类实现了OnClickListener,界面中所有点击操作使用子类作为监听器即可</p>
	 */
	// @Override
	// public abstract void onClick(View arg0);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		Window window = this.getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//		window.setStatusBarColor(Color.parseColor("#168CD5"));

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏

		activityList.add(this);
//		IMApplication.getInstance().currentActivity = this;
		F = new F(this);
		F.id(0).image("", false, true, 50, 50, null, 0, 1.5f);
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		S.init(getApplicationContext());
		//暂时屏蔽
		S.DisplayService.init(this);
//		F.id(R.id.public_btn_left).clicked(this);
		sharedPreferences = getSharedPreferences("istudy", 0);
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//			setTranslucentStatus(true);
//		}
//
		Rect rect = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
		top = getStatusBarHeight();
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）
		hight = metric.heightPixels; // 屏幕高度（像素）
		density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
	
//		SystemBarTintManager tintManager = new SystemBarTintManager(this);
//		tintManager.setStatusBarTintEnabled(true);
//		tintManager.setStatusBarTintResource(R.color.public_title_bg);//通知栏所需颜色
		  
		// if (S.AppService.ifDebug) {
		// StrictMode.setThreadPolicy(new
		// StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
		// .detectNetwork() // or .detectAll() for all detectable
		// // problems
		// .penaltyLog().build());
		// StrictMode.setVmPolicy(new
		// StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
		// .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
		// }
		IntentFilter filter = new IntentFilter();        
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//        registerReceiver(mNetworkStateReceiver, filter);
		ShortcutBadger.removeCount(this);
	}
//	@TargetApi(19) 
//	private void setTranslucentStatus(boolean on) {
//		Window win = getWindow();
//		WindowManager.LayoutParams winParams = win.getAttributes();
//		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//		if (on) {
//			winParams.flags |= bits;
//		} else {
//			winParams.flags &= ~bits;
//		}
//		win.setAttributes(winParams);
//	}
	@Override
	protected void onDestroy() {
		unregisterReceiverSafe(mNetworkStateReceiver);
		super.onDestroy();	
    }	
	
	private void unregisterReceiverSafe(BroadcastReceiver receiver) {
	    try 
	    {
	        this.unregisterReceiver(receiver);
	    }
	    catch (IllegalArgumentException e){}
	}

	@Override
	public void onBackPressed() {
		if (ifShowExit) {
			if (System.currentTimeMillis() - preKeyBackTime < 2000) {
				finishAll();
				S.AppService.killAppProcess();
			} else {
				preKeyBackTime = System.currentTimeMillis();
				U.Toast(this, exitMsg, exitImgID);
			}
			// U.Dialog(this).showSelect("确定退出应用吗?", null, new
			// Dialog.OnClickListener() {
			// @Override
			// public void onClick(DialogInterface arg0, int arg1) {
			// finishAll();
			// S.AppService.killAppProcess();
			// }
			// }, null);
		} else {
			this.finish();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
//		case R.id.public_btn_left:
//			finish();
//			break;
		default:
			break;
		}
	}



	@Override
	protected void onResume() {
		if(mNetErrorView!=null&&public_layout_top!=null)
		{
			if (!NetworkType.isConnect(this)){
				ViewTreeObserver vto = public_layout_top.getViewTreeObserver();
				vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

				@Override
				public void onGlobalLayout() {
				// TODO 自动生成的方法存根
					top2=public_layout_top.getHeight();
				}
				});
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
						width,
						(int) (hight-top-top2-0.5*density-2));
				mNetErrorView.setLayoutParams(lp);
				mNetErrorView.setVisibility(View.VISIBLE);
				}
			else {
				mNetErrorView.setVisibility(View.GONE);
				}
		}
		clipboardIntit();
		if (isOne) {
			goodsDetailsData();
		}
		isOne = false;
		super.onResume();
//		Bugtags.onResume(this);
	}

	protected void COCOKeyBack(boolean _exit) {
		ifShowExit = _exit;
	}

	protected void COCOKeyBack(boolean _exit, String _exitMsg, int _toastImgID) {
		COCOKeyBack(_exit);
		exitImgID = _toastImgID;
		exitMsg = _exitMsg;
	}
	
	protected void onInitNetStateView(LinearLayout mNetErrorView,RelativeLayout public_layout_top)
	{
		this.mNetErrorView=mNetErrorView;
		this.public_layout_top=public_layout_top;
		this.mNetErrorView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
			}
		});
	}
	protected void hide(View view){
		this.view=view;
	}
	BroadcastReceiver mNetworkStateReceiver = new BroadcastReceiver() 
	{        
    	@Override
        public void onReceive(Context context, Intent intent)
    	{
    		if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
    		{
	    		if(mNetErrorView!=null)
	    		{
		        	if(!isConnectingToInternet())
		        	{  
		        		if(mNetErrorView.getVisibility()==View.GONE){
		        			if (null!=view) {
		        				view.setVisibility(view.VISIBLE);
							}
		        			U.Toast(context, "无网络连接，请检查网络");
		        		}
//		        		if(mNetErrorView.getVisibility()==View.GONE)
//		        		{
//		        			ViewTreeObserver vto = public_layout_top.getViewTreeObserver();
//		    				vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//
//		    				@Override
//		    				public void onGlobalLayout() {
//		    				// TODO 自动生成的方法存根
//		    					top2=public_layout_top.getHeight();
//		    				}
//		    				});
//		    				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
//		    						width,
//		    						(int) (hight-top-top2));
//		    				mNetErrorView.setLayoutParams(lp);
//		        			mNetErrorView.setVisibility(View.VISIBLE);
////		        			TextView net_status_bar_info_top=(TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top);
////		        			net_status_bar_info_top.setText(context.getResources().getString(R.string.notify_no_network));
//		        		}
		        	}
		        	else
		        	{
		        		if(mNetErrorView.getVisibility()==View.VISIBLE)
		        			mNetErrorView.setVisibility(View.VISIBLE);
		        		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
								1,
								1);
						mNetErrorView.setLayoutParams(lp);
		        			if (null!=view) {
		        				view.setVisibility(view.VISIBLE);
							}
		        	}
	    		}
    		}
    	}
    };
    public int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height",
				"dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}
    public boolean isConnectingToInternet()
	{  
        ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
        if (connectivity != null)  
        {  
	       	 NetworkInfo[] info = connectivity.getAllNetworkInfo();  
	       	 if (info != null)  
	       	 {
	       		 for (int i = 0; i < info.length; i++) 
	       		 {
	       			 if (info[i].getState() == NetworkInfo.State.CONNECTED)  
	       			 {
	       				 return true;  
	       			 }  
	       		 }
	       	 }
        }  
        return false;
    }

	public  class EditChangedListener implements TextWatcher {
		private EditText edit_other_amount;
		public EditChangedListener(EditText edit_other_amount) {
			this.edit_other_amount = edit_other_amount;
		}
		private CharSequence temp;//监听前的文本
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			String  aa = edit_other_amount.getText().toString();
			if (!TextUtils.isEmpty(aa)) {
				if (aa.substring(0,1).equals(".")) {
					edit_other_amount.setText("");
				}
				else if (aa.indexOf(".") != -1) {
					edit_other_amount.setKeyListener(new NumberKeyListener() {
						@Override
						protected char[] getAcceptedChars() {
							return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
						}
						@Override
						public int getInputType() {
							return android.text.InputType.TYPE_CLASS_PHONE;
						}
					});
					if (aa.length()>3) {
						String[] bb = aa.split("\\.");
						if (bb.length > 1) {
							if (!TextUtils.isEmpty(bb[1])) {
								if (bb[1].length() > 2) {
									edit_other_amount.setText(aa.substring(0, aa.length() - 1));
									edit_other_amount.setSelection( edit_other_amount.getText().toString().length());
								}
							}
						}
					}
				} else if  (aa.substring(0,1).equals("0")&& aa.length()==1) {
					edit_other_amount.setKeyListener(new NumberKeyListener() {
						@Override
						protected char[] getAcceptedChars() {
							return new char[]{'.'};
						}
						@Override
						public int getInputType() {
							return android.text.InputType.TYPE_CLASS_PHONE;
						}
					});
				}
				else {
					edit_other_amount.setKeyListener(new NumberKeyListener() {
						@Override
						protected char[] getAcceptedChars() {
							return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0','.'};
						}
						@Override
						public int getInputType() {
							return android.text.InputType.TYPE_CLASS_PHONE;
						}
					});
				}
			}  else {
				edit_other_amount.setKeyListener(new NumberKeyListener() {
					@Override
					protected char[] getAcceptedChars() {
						return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'};
					}

					@Override
					public int getInputType() {
						return android.text.InputType.TYPE_CLASS_PHONE;
					}
				});
			}
		}
	};


	//================================================弹出口令窗口==========================================

	/**
	 * 详情接口
	 */
	public void goodsDetailsData() {
		Map<String, String> formMap = new HashMap<String, String>();
		String url = Setting.GOODS_DETAILS;
		formMap.put("url_id",content);
		formMap.put("field","goods_name,shop_price_rm,img_list");
		GetHttps( url, formMap, 200);
	}

	private   static String content  ="";

	/**
	 * c获取剪切板
	 */
	public void clipboardIntit() {
		ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		//无数据时直接返回
		if (!cm.hasPrimaryClip()) {
			return;
		}
		//如果是文本信息
		if (cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
			ClipData cdText = cm.getPrimaryClip();
			ClipData.Item item = cdText.getItemAt(0);
			if(null == item.getText()){
				return;
			}
			String url = item.getText().toString();

			SharedPreferences languagePre = getSharedPreferences("language_choice",
					Context.MODE_PRIVATE);
			String con = languagePre.getString("jian_qie","");
			if (url.equals(con)){
				return;
			}
//			//淘宝,天猫,京东,飞猪,唯品会,当当网,美丽说,蘑菇街,asia5b,1号店,亚马逊,拼多多
//			if (url.indexOf("￥") > -1 ||url.indexOf("zmnxbc.com") > -1 || url.indexOf("item.m.jd.com")>-1|| url.indexOf("m.vip.com")>-1
//					|| url.indexOf("product.m.dangdang.com")>-1|| url.indexOf("m.meilishuo.com")>-1|| url.indexOf("h5.mogujie.com")>-1
//					|| url.indexOf("asia5b.com")>-1|| url.indexOf("item.m.yhd.com")>-1|| url.indexOf("amazon.com")>-1|| url.indexOf("yangkeduo.com")>-1) {
				SharedPreferences.Editor editor = languagePre.edit();
				editor.putString("jian_qie", url);
				editor.commit();
				isOne = true;
				try {
					content =url;
				}catch (Exception e){}
//			}
		}
	}
	public void clipboard() {
		final  ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		cm.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
			@Override
			public void onPrimaryClipChanged() {
				ClipData data = cm.getPrimaryClip();
				ClipData.Item item = data.getItemAt(0);
				if(null == item.getText()){
					return;
				}
				String url = item.getText().toString();
//				//淘宝,天猫,京东,飞猪,唯品会,当当网,美丽说,蘑菇街,asia5b,1号店,亚马逊,拼多多
//				if (url.indexOf("￥") > -1 ||url.indexOf("zmnxbc.com") > -1 || url.indexOf("item.m.jd.com")>-1|| url.indexOf("m.vip.com")>-1
//						|| url.indexOf("product.m.dangdang.com")>-1|| url.indexOf("m.meilishuo.com")>-1|| url.indexOf("h5.mogujie.com")>-1
//						|| url.indexOf("asia5b.com")>-1|| url.indexOf("item.m.yhd.com")>-1|| url.indexOf("amazon.com")>-1|| url.indexOf("yangkeduo.com")>-1) {
					isOne = true;
					try {
						content =url;
					}catch (Exception e){}
//				}
			}
		});
	}


	Dialog alertDialog = null;
	private void initDialog(String imgurl,String name,String price_rm) {
		if (null == alertDialog) {
			alertDialog = new Dialog(BaseActivity.this, R.style.CustomDialogStyle);
		}
		LayoutInflater inflater = (LayoutInflater) BaseActivity.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.command_dialog, null);
		ImageView image_del = (ImageView)  view.findViewById(R.id.image_del);
		ImageView image_thumb = (ImageView) view.findViewById(R.id.image_thumb);
		TextView txt_goods_name = (TextView) view.findViewById(R.id.txt_goods_name);
		TextView txt_shop_price_rm = (TextView)view.findViewById(R.id.txt_shop_price_rm);
		Button btn_immediately_on = (Button)view.findViewById(R.id.btn_immediately_on);

		DownloadPicture.loadHearNetwork(imgurl,image_thumb);
		txt_goods_name.setText(name);
		txt_shop_price_rm.setText("RM "+price_rm);
		btn_immediately_on.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(BaseActivity.this, CommodityDetActivity.class);
				intent.putExtra("tmall",content);
				startActivity(intent);
				alertDialog.dismiss();
			}
		});
		// 返回按键
		alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				alertDialog.dismiss();
			}
		});
		image_del.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				alertDialog.dismiss();
			}
		});
		alertDialog.setCancelable(true);
		alertDialog.show();
		alertDialog.getWindow().setContentView(view);
	}

	private Handler handler6 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			JSONObject result = null;
			try {
				result = new JSONObject(msg.obj.toString());
			} catch (Exception e) {
			}
			int action = msg.what;
			if (action == 200) {
				if (null != result && result instanceof JSONObject) {
					try {
						JSONObject json = (JSONObject) result;
						int state = (int) json.getInt("State");
						if (state == 0) {
							JSONObject goods = json.getJSONObject("goods");
							String goods_name = goods.getString("goods_name");
							String txt_shop_price_rm = goods.getString("shop_price_rm");
							String img_url = "";
							JSONObject img_list = goods.getJSONObject("img_list");
							Iterator<String> iter3 = img_list.keys();
							boolean isEd = true;
							while(iter3.hasNext()){
								String keyStr = iter3.next();
								JSONObject im = img_list.getJSONObject(keyStr);
								img_url = im.getString("img_url");
								break;
							}
							initDialog(img_url,goods_name,txt_shop_price_rm);
						}
//                        else {
//                            U.Toast(MainActivity.this,getResources().getString(R.string.hqyc));
//                        }
					} catch (Exception e) {
					}
				}
			}
		}

	};


	public  void GetHttps( String url, Map<String, String> param, final int action) {
		StringBuffer sb1 = new StringBuffer();
		for (Map.Entry<String, String> entry : param.entrySet()) {
			sb1.append("&");
			sb1.append(entry.getKey());
			sb1.append("=");
			sb1.append(entry.getValue());
		}

		String url22 = url + sb1.toString();
		Log.e("3333333333333333333333333333333333",url22);
		try {
			FormBody.Builder builder = new FormBody.Builder();
			for (Map.Entry<String, String> entry : param.entrySet()) {
				builder.add(entry.getKey(),entry.getValue());
			}
			RequestBody requestBodyPost = builder.build();
			Request requestPost = new Request.Builder().url(url).
					post(requestBodyPost)
					.build();
			OkHttpClient a = JsonTools2.getInitOkHttp();
			Call b = a.newCall(requestPost);
			Callback callback = new Callback() {
				@Override
				public void onFailure(Call call, IOException e) {
					System.out.print(e.getMessage());
				}

				@Override
				public void onResponse(Call call, Response response) {
					try {
						String jsonStr = response.body().string();
						JSONObject json = new JSONObject(jsonStr);
						Message msg = new Message();
						msg.what = action;
						msg.obj = json.toString();
						handler6.sendMessage(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			b.enqueue(callback);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
